<template>
  <div class="attendance-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Clock /></el-icon>
            <span class="header-title">考勤打卡</span>
          </div>
        </div>
      </template>
      
      <div class="action-section">
        <div class="action-buttons">
          <el-button 
            type="primary" 
            size="large" 
            @click="handleCheckIn" 
            :disabled="checkInDisabled"
            class="action-btn checkin-btn"
          >
            <el-icon><CircleCheck /></el-icon>
            <span>上班打卡</span>
          </el-button>
          <el-button 
            type="success" 
            size="large" 
            @click="handleCheckOut" 
            :disabled="checkOutDisabled"
            class="action-btn checkout-btn"
          >
            <el-icon><CircleClose /></el-icon>
            <span>下班打卡</span>
          </el-button>
          <el-button 
            type="warning" 
            size="large" 
            @click="showSupplementDialog = true"
            class="action-btn"
          >
            <el-icon><Edit /></el-icon>
            <span>申请补卡</span>
          </el-button>
        </div>
      </div>
      
      <el-divider />
      
      <div class="table-section">
        <el-table 
          :data="attendanceList" 
          style="width: 100%"
          :empty-text="'暂无考勤记录'"
          stripe
        >
          <el-table-column prop="type" label="类型" width="120" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.type === 'CHECK_IN'" type="success" effect="dark">
                <el-icon><CircleCheck /></el-icon>
                上班
              </el-tag>
              <el-tag v-else-if="scope.row.type === 'CHECK_OUT'" type="info" effect="dark">
                <el-icon><CircleClose /></el-icon>
                下班
              </el-tag>
              <el-tag v-else type="warning" effect="dark">
                <el-icon><Timer /></el-icon>
                加班
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="checkInTime" label="打卡时间" width="180" align="center">
            <template #default="scope">
              <span class="time-text">{{ formatDate(scope.row.checkInTime || scope.row.checkOutTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 'APPROVED'" type="success">已通过</el-tag>
              <el-tag v-else-if="scope.row.status === 'PENDING'" type="warning">待审核</el-tag>
              <el-tag v-else type="danger">已拒绝</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="异常情况" width="150" align="center">
            <template #default="scope">
              <div v-if="scope.row.isLate || scope.row.isEarlyLeave || scope.row.isAbsent" class="exception-tags">
                <el-tag v-if="scope.row.isLate" type="danger" size="small">迟到{{ scope.row.lateMinutes }}分钟</el-tag>
                <el-tag v-if="scope.row.isEarlyLeave" type="warning" size="small">早退{{ scope.row.earlyLeaveMinutes }}分钟</el-tag>
                <el-tag v-if="scope.row.isAbsent" type="danger" size="small">缺勤</el-tag>
              </div>
              <span v-else class="normal-text">正常</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="scope">
              <span class="time-text">{{ formatDate(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 补卡申请弹窗 -->
    <el-dialog
      v-model="showSupplementDialog"
      title="申请补卡"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="supplementFormRef"
        :model="supplementForm"
        :rules="supplementRules"
        label-width="100px"
      >
        <el-form-item label="补卡日期" prop="date">
          <el-date-picker
            v-model="supplementForm.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="补卡类型" prop="type">
          <el-radio-group v-model="supplementForm.type">
            <el-radio label="CHECK_IN">上班打卡</el-radio>
            <el-radio label="CHECK_OUT">下班打卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="补卡时间" prop="time">
          <el-time-picker
            v-model="supplementForm.time"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="补卡原因" prop="reason">
          <el-input
            v-model="supplementForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入补卡原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSupplementDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitSupplement" :loading="supplementLoading">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { Clock, CircleCheck, CircleClose, Edit, Timer } from '@element-plus/icons-vue'

export default {
  name: 'Attendance',
  components: {
    Clock,
    CircleCheck,
    CircleClose,
    Edit,
    Timer
  },
  setup() {
    const attendanceList = ref([])
    const checkInDisabled = ref(false)
    const checkOutDisabled = ref(false)
    const showSupplementDialog = ref(false)
    const supplementFormRef = ref(null)
    const supplementLoading = ref(false)
    
    const supplementForm = ref({
      date: '',
      type: 'CHECK_IN',
      time: '',
      reason: ''
    })
    
    const supplementRules = {
      date: [
        { required: true, message: '请选择补卡日期', trigger: 'change' }
      ],
      type: [
        { required: true, message: '请选择补卡类型', trigger: 'change' }
      ],
      time: [
        { required: true, message: '请选择补卡时间', trigger: 'change' }
      ],
      reason: [
        { required: true, message: '请输入补卡原因', trigger: 'blur' }
      ]
    }
    
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString('zh-CN')
    }
    
    const loadAttendanceList = async () => {
      try {
        const res = await request.get('/attendance/my')
        attendanceList.value = res.data || []
      } catch (error) {
        ElMessage.error('加载考勤记录失败')
      }
    }
    
    const handleCheckIn = async () => {
      try {
        await request.post('/attendance/checkin')
        ElMessage.success('打卡成功')
        checkInDisabled.value = true
        loadAttendanceList()
      } catch (error) {
        ElMessage.error(error.message || '打卡失败')
      }
    }
    
    const handleCheckOut = async () => {
      try {
        await request.post('/attendance/checkout')
        ElMessage.success('下班打卡成功')
        checkOutDisabled.value = true
        loadAttendanceList()
      } catch (error) {
        ElMessage.error(error.message || '打卡失败')
      }
    }
    
    // 提交补卡申请
    const handleSubmitSupplement = async () => {
      if (!supplementFormRef.value) return
      
      try {
        await supplementFormRef.value.validate()
        supplementLoading.value = true
        
        const res = await request.post('/attendance/supplement', {
          date: supplementForm.value.date,
          type: supplementForm.value.type,
          time: supplementForm.value.time,
          reason: supplementForm.value.reason
        })
        
        if (res.code === 200) {
          ElMessage.success('补卡申请已提交')
          showSupplementDialog.value = false
          supplementForm.value = {
            date: '',
            type: 'CHECK_IN',
            time: '',
            reason: ''
          }
          loadAttendanceList()
        } else {
          ElMessage.error(res.message || '提交失败')
        }
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('提交失败')
        }
      } finally {
        supplementLoading.value = false
      }
    }
    
    onMounted(() => {
      loadAttendanceList()
    })
    
    return {
      attendanceList,
      checkInDisabled,
      checkOutDisabled,
      showSupplementDialog,
      supplementForm,
      supplementFormRef,
      supplementRules,
      supplementLoading,
      formatDate,
      handleCheckIn,
      handleCheckOut,
      handleSubmitSupplement
    }
  }
}
</script>

<style scoped>
.attendance-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.action-section {
  margin-bottom: 24px;
}

.action-buttons {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.action-btn {
  flex: 1;
  min-width: 150px;
  height: 56px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.checkin-btn {
  background: #409eff;
  border-color: #409eff;
}

.checkout-btn {
  background: #67c23a;
  border-color: #67c23a;
}

.table-section {
  margin-top: 24px;
}

.time-text {
  color: #666;
  font-size: 14px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}

.exception-tags {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.normal-text {
  color: #67c23a;
  font-size: 14px;
}
</style>

